package com.wswy.wzcx.ui.wzdb

import android.content.Context
import android.support.v4.content.ContextCompat
import android.text.TextUtils
import android.util.AttributeSet
import android.view.View
import android.widget.RelativeLayout
import com.facebook.common.util.UriUtil
import com.facebook.drawee.drawable.ScalingUtils
import com.wswy.wzcx.R
import com.wswy.wzcx.model.wzdb.AddUserCertEntry
import com.wswy.wzcx.utils.FrescoUtils
import kotlinx.android.synthetic.main.layout_cert_photo_item.view.*
import java.io.File

class CertCardSelectView : RelativeLayout, IInputView {

    constructor(context: Context) : this(context, null)

    constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)

    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {

        View.inflate(context, R.layout.layout_cert_photo_item, this)

        //setBackgroundResource(R.drawable.bg_cert)
        isClickable = true

        val typedArray = context.obtainStyledAttributes(attrs, R.styleable.CertCardSelectView)

        val text = typedArray.getText(R.styleable.CertCardSelectView_android_text)
        val textColor = typedArray.getColor(R.styleable.CertCardSelectView_android_textColor, ContextCompat.getColor(context, R.color.textColorPrimary))
        typedArray.recycle()

        tv_photo_title.setTextColor(textColor)
        tv_photo_title.text = text
    }


    var imgPath: String? = null
        set(value) {

            val oldPath = imgPath
            if (!TextUtils.isEmpty(oldPath) && !TextUtils.equals(value, oldPath)) {
                File(oldPath).delete()
            }
            if (value != null) {
                UriUtil.getUriForFile(File(value))?.let {

                    if (certEntry?.alias != "OUP") {
                        //自拍特殊处理
                        img_phone?.hierarchy?.actualImageScaleType = ScalingUtils.ScaleType.CENTER
                    }

                    FrescoUtils.removeCache(it)
                    img_phone.setImageURI(it, null)

                }
            }
            field = value

        }


    var certEntry: AddUserCertEntry? = null

    override fun bindEntry(index: Int, entry: AddUserCertEntry?) {
        certEntry = entry
        tv_photo_title.text = certEntry?.label
    }


    override fun getInfo(): AddUserCertEntry? {
        return certEntry
    }

    override fun getValue(): File? {
        val path = imgPath
        return if (path.isNullOrEmpty()) null else File(path)
    }

}